<script setup lang="ts">
  import { ref, reactive, watch } from 'vue'
  import { dispatchOrderEmp } from '@/api/order'
  import useCustomerServiceOption from './useCustomerServiceOptions'
  import { ElMessage } from 'element-plus'
  import _ from 'lodash'
  import HButton from '@/components/common/button/HButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import type { FormInstance } from 'element-plus'

  const props = defineProps({
    selecttion: {
      type: Array,
      required: true,
    },
    isBatch: {
      type: Boolean,
      required: true,
    },
    modelValue: {
      type: Boolean,
      default: () => false,
    },
    emp: String,
  })

  const emits = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'update'): void
  }>()

  /**
   * 保存加载
   */
  const saveLoading = ref(false)

  /**
   * 表单组件实例
   */
  const formRef = ref<FormInstance | null>(null)

  /**
   * 表单
   */
  const form = ref({
    empId: '',
  })

  /**
   * 弹窗的显示状态
   */
  const visible = ref(false)

  /**
   * 表单的验证规则
   */
  const rules = reactive({
    empId: [{ required: true, message: '请选择客服人员！', trigger: ['blur', 'change'] }],
  })

  const { customerServiceOptions, getCustomerServiceOptionsLoading, getCustomerServiceOptions } =
    useCustomerServiceOption

  /**
   * 获取客服下拉选项的搜索关键字
   */
  const getCustomerServiceOptionsKeyword = ref('')

  /**
   * 获取客服人员下拉选项
   */
  const handleGetCustomerServiceOptions = _.throttle((val: string) => {
    if (getCustomerServiceOptionsKeyword.value !== val) {
      getCustomerServiceOptions(getCustomerServiceOptionsKeyword.value)
    }
  }, 500)

  /**
   * 保存
   */
  const onSave = async () => {
    try {
      await formRef.value.validate()
      saveLoading.value = true
      const res = await dispatchOrderEmp(props.selecttion, form.value.empId)
      if (!res) return
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          duration: 3000,
          type: res.data.success ? 'success' : 'error',
        })
      if (res.data.success) {
        emits('update')
        onCancel()
      }
      saveLoading.value = false
    } catch (e) {
      // 表单验证失败
    }
  }

  /**
   * 取消
   */
  const onCancel = () => {
    formRef.value.resetFields()
    form.value.empId = ''
    visible.value = false
    emits('update:modelValue', visible.value)
  }

  watch(
    props,
    (value) => {
      visible.value = value.modelValue
      if (visible.value) {
        getCustomerServiceOptions('')
      }
    },
    { immediate: true, deep: true },
  )
</script>

<template>
  <HModal v-model="visible" @close="onCancel" size="small">
    <template #header>
      <h3><span v-if="props.isBatch">批量</span>分配客服</h3>
    </template>
    <div v-loading="saveLoading" element-loading-text="加载中...">
      <div v-if="props.isBatch" class="title">
        <span>当前选中&nbsp;</span>
        <span class="num">{{ selecttion.length }}</span>
        <span>&nbsp;个工单进行批量操作！</span>
      </div>
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-form-item label="分配客服" required prop="empId">
          <el-select
            v-model="form.empId"
            placeholder="分配客服"
            filterable
            clearable
            :filter-method="handleGetCustomerServiceOptions"
            :loading="getCustomerServiceOptionsLoading"
            remote-show-suffix
          >
            <el-option
              v-for="item in customerServiceOptions"
              :key="item.name"
              :disabled="props.emp === item.name"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footerRight>
      <HButton isModal type="primary" @click="onSave">保存</HButton>
      <HButton isModal @click="onCancel">取消</HButton>
    </template>
  </HModal>
</template>

<style scoped lang="scss">
  @import './AssignCustomerService.scss';
</style>
